<template>
  <div>
    <!-- 设备树结构--组件 -->
    <deviceTree ref="deviceTree1" @send_selectID="checked_change"></deviceTree>
    <div id="graphContainer2"></div>
    <!-- socket状态组件 -->
    <socketStatus ref="socketStatus1" :send_data="send_socketArr"></socketStatus>
  </div>
</template>
 
<script>
import deviceTree from './statusModal/deviceTree.vue'
import socketStatus from './statusModal/socketStatus'
import "./graph/Init";
import mxgraph from "./graph/index";
import Toolbar from "./graph/Toolbar";
import EditorUi from "./graph/EditorUi2";
import Editor from "./graph/Editor";
import "./graph/Shapes";
import UrlParams from "./graph/UrlParams";
import { Menus } from "./graph/Menus";
import grapheditorTxt from "./resources/grapheditor.txt";
import defaultXml from "./styles/default.xml";
import graphApi from "../../api/graph.api";

const {
  mxGraph,
  mxConstants,
  mxOutline,
  mxEvent,
  mxCell,
  mxGeometry,
  mxUtils,
  mxEventObject,
  mxConnectionHandler,
  mxRubberband,
  mxToolbar,
  mxResources,
  mxCodec
} = mxgraph;

import { Graph } from "./graph/Graph";
import { setTimeout, setInterval } from "timers";
export default {
  components: { deviceTree, socketStatus },
  data() {
    return {
      webstock: null, // new WebSocket(http_ip);
      send_socketArr: [], //父传给子组件的变量
      new_arry: [],
      checkedId: "",
      name: "",
      xml: null,
      showXmlData: [], //xml数据
      new_showXmlData: [],
      flage: false
    }
  },
  methods: {
    //子组件-deviceTree.vue 传过来的selectid
    checked_change(id){
      if(id){
        console.log("id:", id);
        this.checkedId = id;
        graphApi.detail(this.checkedId).then(res => {
          //页面销毁时关闭长连接
          if (this.webstock !== null) {
            this.webstock.close(); //关闭websocket
          }
          let data = res.data.data;
          this.name = data.name;
          this.xml = data.xml;
          this.init();
          console.log("deviceid是否存在：",this.send_socketArr);
          if( this.send_socketArr.length > 0){
            // this.$refs.socketStatus1.socket(); //调子组件的方法
            this.socket(); //封装websocket
          }
        })
      }
    },

    init() {
      let self = this;
      let editorUiInit = EditorUi.prototype.init;
      EditorUi.prototype.init = function() {
        editorUiInit.apply(this, arguments);
        // console.log(editorUiInit,this)
        // editorUiInit.toolbar = false;
        // Updates action states which require a backend
        // this.actions.get("open").setEnabled(false);
        // this.actions.get("lockUnlock").setEnabled(false);
      };

      // Adds required resources (disables loading of fallback properties, this can only
      // be used if we know that all keys are defined in the language specific file)
      mxResources.loadDefaultBundle = false;
      mxResources.parse(grapheditorTxt);

      // Configures the default graph theme
      var themes = new Object();
      themes[Graph.prototype.defaultThemeName] = mxUtils.parseXml(
        defaultXml
      ).documentElement;

      // Main
      let mEditorUi = new EditorUi(
        new Editor(UrlParams["chrome"] == "0", themes),
        document.getElementById("graphContainer2")
      );
      let mGraph = mEditorUi.editor.graph;
      mGraph.setEnabled(false); // 不可编辑设置
      mGraph.getView().updateStyle = true; // 动态改变样式
      mGraph.setResizeContainer(true);// 容器大小自适应
      mGraph.setCellsResizable(false);// 禁止改变元素大小 
      mGraph.edgeLabelsMovable = false; // 禁用移动标签
      mGraph.setVertexLabelsMovable(true); // 允许移动 Vertex 的 Label
      if (self.xml) {
        mEditorUi.editor._id = self.id;
        mEditorUi.editor.filename = self.name;
        mGraph.getModel().beginUpdate(); // 开启更新
        try {
          const doc = mxUtils.parseXml(self.xml);
          const root = doc.documentElement;
          const dec = new mxCodec(root.ownerDocument);
          dec.decode(root, mGraph.getModel());
          // console.log( "doc:", doc, dec, dec.decode(root, mGraph.getModel()));
          // console.log("111:",dec, dec.objects);

          var xmlArry = dec.objects;
          self.showXmlData = dec.objects;

          xmlArry.map(v=>{
            if ( v.deviceId && v.deviceId !== undefined ) {
              v.deviceId = v.deviceId.toString(); //转成字符串
              // _num传入的数字，m需要的字符长度
              let _num = v.deviceId;
              let m = 17;
              function PrefixInteger(_num, m) {
                return (Array(m).join(0) + _num).slice(-m);
              }
              // console.log((Array(m).join(0) + _num).slice(-m))
              v.deviceId = (Array(m).join(0) + _num).slice(-m);

              self.send_socketArr.push(v.deviceId);
              self.send_socketArr = [...new Set(self.send_socketArr)];
              // console.log(v, self.send_socketArr);
            } else {
              //如果没有deviceId就return
              return false;
            }
          })
        } finally {
          mGraph.getModel().endUpdate(); // 结束更新
        }
      }
      //有级别value走
      if (this.flage == true){
        for (let k = 0; k < this.new_showXmlData.length; k++) {
          mGraph.getModel().beginUpdate(); // 开启更新
          try {
              //未绑定id的
              var newS = {
                fillColor: "black",
                strokeColor: "black"
              };
              var showStatusName = ""; //设备状态文字提示
              if(this.new_showXmlData[k].deviceId && this.new_showXmlData[k].statusLevel){
                showStatusName = this.new_showXmlData[k].statusValue;
                if( this.new_showXmlData[k].statusLevel == 0){
                  var newS = {
                    fillColor: "black",
                    strokeColor: "black"
                  };
                } else if( this.new_showXmlData[k].statusLevel == 1){
                  var newS = {
                    fillColor: "yellow",
                    strokeColor: "yellow"
                  };
                }else if( this.new_showXmlData[k].statusLevel == 2){
                  var newS = {
                    fillColor: "pink",
                    strokeColor: "pink"
                  };                     
                }else if( this.new_showXmlData[k].statusLevel == 3){
                  var newS = {
                    fillColor: "purple",
                    strokeColor: "purple"
                  };                       
                }else if( this.new_showXmlData[k].statusLevel == 4){
                  var newS = {
                    fillColor: "red",
                    strokeColor: "red"
                  };
                }else if( this.new_showXmlData[k].statusLevel == -1){
                  var newS = {
                    fillColor: "gray",
                    strokeColor: "gray"
                  };
                }else {
                  showStatusName = this.new_showXmlData[k].statusValue;
                  var newS = {
                    fillColor: "black",
                    strokeColor: "black"
                  };
                }
              }

              let newCell = xmlArry[k];
              newS = newS;
              // console.log("newS:",newS);
              newUpdateStyle(newCell, newS, showStatusName);//回调下面的fun
              //更新视图
              mGraph.refresh();
              /*
                * newCell: 当前的 cell 对象
                * newStyleObj： 新的样式对象
                */
              function newUpdateStyle(newCell, newStyleObj, showStatusName) {
                //newCell里面有style才走
                if( newCell.style){
                  //判断newCell.style是否同时包含：fillColor,strokeColor
                  let _str = newCell.style;
                  if( _str.indexOf("html") != -1 && _str.indexOf("fillColor") != -1 && _str.indexOf("strokeColor") != -1){

                    let oldStylesArr = [];
                    let temp = newCell.style.split(";"); // ["shape=xor", "whiteSpace=wrap", "html=1", "fillColor=green", "strokeColor=blue", ""]
                    temp.map(v => {
                      let styleObj = {
                        name: v.split("=")[0],
                        value: v.split("=")[1]
                      };
                      oldStylesArr.push(styleObj); // [ {name: 'fillColor', value: 'green'},...]
                    });
                    // console.log(temp, oldStylesArr);
        
                    let resultStyleStr = "";
                    oldStylesArr.map((v, index) => {
                      if (v.name == "fillColor") {
                        v.value = newStyleObj["fillColor"];
                      }
                      if (v.name == "strokeColor") {
                        v.value = newStyleObj["strokeColor"];
                      }
                      resultStyleStr +=
                        v.name +
                        (v.value ? "=" + v.value : "") +
                        (index == oldStylesArr.length - 1 ? "" : ";");
                    });
                    // console.log("resultStyle:", resultStyleStr);
                    newCell.style = resultStyleStr;
                  }
                }
                //设备状态文字提示
                mGraph.setAttributeForCell(newCell, '设备状态', showStatusName);
                mGraph.setAttributeForCell(newCell, '设备级别', showStatusName);
              }
          } finally {
            mGraph.getModel().endUpdate(); // 结束更新
          }
        }
      }
    },

    //封装websocket
    socket() {
      if (typeof WebSocket != "undefined") {
        this.initWebSocket(); // 开启WebSocket长连接
      } else {
        this.$alert("您的浏览器不支持Websocket通信协议，请使用Chrome或者Firefox浏览器！","温馨提示：");
      }
    },
    /**
     * webstocket 开启长连接
     */
    initWebSocket() {
      //页面刚进入时开启长连接
      // const http_ip ="ws://" +this.$store.state.user.Websocket_AlarmDispatchSrv_ip +":" +
      // this.$store.state.user.Websocket_AlarmDispatchSrv_port;
      const http_ip = "ws://192.168.25.41:7001/";
      this.webstock = new WebSocket(http_ip);
      // console.log("ip:", http_ip);
      this.webstock.onopen = this.webstockonopen;
      this.webstock.onmessage = this.webstockonmessage;
      this.webstock.onclose = this.webstockclose;
      this.webstock.onerror = this.webstockonerror;
    },
    /**
     * webstock连接成功
     */
    webstockonopen(onopen) {
      // console.log("websocket open 连接成功", onopen,this.send_socketArr,this.showXmlData);
      this.webstock.send(JSON.stringify(this.send_socketArr));
    },
    /**
     * webstock接收消息
     */
    webstockonmessage(message) {
      let webstockArr = JSON.parse(message.data);
      // console.log("返回webstockArr:", webstockArr);
      if (webstockArr == "") {
        // this.$alert("websocket未连接，加载Topo图初始状态","温馨提示：");
      } else {
        // debugger;
        if ( this.showXmlData.length <= 0 ) return false;
        if ( webstockArr.length <= 0 ){
          return false;
        } else {
          webstockArr.map(k=>{
            let index = this.new_arry.findIndex(v => v.id === k.deviceId)
            if( index > -1) {
              this.new_arry[index].name = k.deviceName
              this.new_arry[index].level = k.alarmLevel
              this.new_arry[index].status = k.alarmValue
            } else {
              this.new_arry.push({id:k.deviceId, name:k.deviceName,level:k.alarmLevel,status:k.alarmValue})
            }
          })
          console.log('组装完成的所有设备信息', this.new_arry)
          this.showXmlData.map(v=>{
            this.new_arry.map(k=>{
              if ( v.deviceId  && v.deviceId == k.id ) {
                //如果设备ID相等 0黑色，1黄色，2粉红色，3紫色，4红色, -1灰色---未知状态
                v.statusLevel = k.level
                v.statusValue = k.status
              } else{
                //如果设备ID不相等，或者deviceId不存在
              }
            })
          })
        }
      }
      console.log("this.showXmlData:", this.showXmlData);
      this.new_showXmlData = this.showXmlData;
      this.$Message.success('加载设备拓扑图成功！');
    },
    /**
     * webstock关闭
     */
    webstockclose(event) {
      console.log("websocket close"); //监听关闭
    },
    /**
     * webstock出错
     */
    webstockonerror(error) {
      // console.log("websocket error");
      this.webstock.close(); //关闭websocket
      this.initWebSocket(); // 开启WebSocket长连接
    }
  },
  watch: {
    //实时监听socket返回数据的new_showXmlData的变化
    new_showXmlData:function(val){
      // console.log("val:",val,val.statusLevel);
      for (let i = 0; i < this.new_showXmlData.length; i++) {
        if(this.new_showXmlData[i].deviceId && this.new_showXmlData[i].statusLevel ){
          this.flage = true;
          this.init();
        }
      }
    }
  },
  created() {},
  mounted() {
    // document.oncontextmenu = function(e) {
    //   return false; //屏蔽右键菜单
    // };
  },
  destroyed() {
    // 销毁 panZoomTiger 实例
    this.$destroy();
    //页面销毁时关闭长连接
    if (this.webstock !== null) {
      this.webstock.close(); //关闭websocket
    }
    this.showXmlData = [];
    this.new_showXmlData = [];  
  }
};
</script>

<style scoped>
@import "./styles/grapheditor.css";
</style>
<style scoped>
>>>#graphContainer2{
  width: 100%;
  height: 100%;
  min-height: 780px !important;
  position: relative;
  top: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
>>>#graphContainer2 .geDiagramContainer.geDiagramBackdrop{
  top: 0px !important;
  width: 100% !important;
  height: 100% !important;
  overflow: hidden !important;
}
>>>#graphContainer2 .geBackgroundPage {
  top: 0px !important;
  left: 0px !important;
  /* width: 3950px !important; */
  width: 100% !important;
  height: 100% !important;
  /* min-height: 700px !important; */
}
>>>#graphContainer2 .geDiagramContainer.geDiagramBackdrop svg{
  /* left: 0px !important; */
  cursor: pointer; /*画布加鼠标小手样式*/
}
</style>